package net.mihome.app.ui;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;

import com.easemob.chat.EMMessage;
import com.easemob.chat.NotificationCompat;
import com.easemob.chatuidemo.utils.CommonUtils;
import com.easemob.util.EasyUtils;
import com.loopj.android.http.RequestParams;

import net.mihome.app.AppContext;
import net.mihome.app.AppManager;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.util.HashMap;
import java.util.Map;

/**
 * 应用程序Activity的基类
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-9-18
 */
public class BaseFragmentActivity extends FragmentActivity {
    protected NotificationManager notificationManager;
    private static final int notifiId = 11;
    private Map<String,User> tempUser=new HashMap<>();

	// 是否允许全屏
	private boolean allowFullScreen = true;

	// 是否允许销毁
	private boolean allowDestroy = true;

	private View view;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		allowFullScreen = true;
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// 添加Activity到堆栈
		AppManager.getAppManager().addActivity(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		// 结束Activity&从堆栈中移除
		AppManager.getAppManager().finishActivity(this);
	}

	public boolean isAllowFullScreen() {
		return allowFullScreen;
	}

	/**
	 * 设置是否可以全屏
	 * 
	 * @param allowFullScreen
	 */
	public void setAllowFullScreen(boolean allowFullScreen) {
		this.allowFullScreen = allowFullScreen;
	}

	public void setAllowDestroy(boolean allowDestroy) {
		this.allowDestroy = allowDestroy;
	}

	public void setAllowDestroy(boolean allowDestroy, View view) {
		this.allowDestroy = allowDestroy;
		this.view = view;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && view != null) {
			view.onKeyDown(keyCode, event);
			if (!allowDestroy) {
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
    /**
     * 当应用在前台时，如果当前消息不是属于当前会话，在状态栏提示一下
     * 如果不需要，注释掉即可
     * @param message
     */
    protected void notifyNewMessage(EMMessage message) {
        //如果是设置了不提醒只显示数目的群组(这个是app里保存这个数据的，demo里不做判断)
        //以及设置了setShowNotificationInbackgroup:false(设为false后，后台时sdk也发送广播)
        if(!EasyUtils.isAppRunningForeground(this)){
            return;
        }

        String ticker = CommonUtils.getMessageDigest(message, this);
        if(message.getType() == EMMessage.Type.TXT)
            ticker = ticker.replaceAll("\\[.{2,3}\\]", "[表情]");
        //设置状态栏提示
        //如果是私聊，状态烂需要显示用户姓名
        String showName=message.getFrom();
        //首先从我的好友中找这个人的资料
            User user= AppContext.getInstance().getOneUser(message.getFrom());
        //找不到就从临时列表中找这个人的资料
        if(user==null){
                user=tempUser.get(message.getFrom());
        }
        //如果还找不到，就异步去获取这个人的资料。然后第一次先显示机器码
        if(user==null){
              loadUser(message.getFrom());
        }
        if(user!=null){
                showName=user.getUsername();
                if(user.getRealName()!=null){
                    showName=showName+"("+user.getRealName()+")";
                }
            }

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainPager.class), 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setContentIntent(contentIntent)
                .setSmallIcon(getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis()).setAutoCancel(true);
        mBuilder.setTicker(showName+": " + ticker);
        // The PendingIntent to launch our activity if the user selects this notification
        Notification notification = mBuilder.build();

        // Set the info for the views that show in the notification panel.
        notificationManager.notify(notifiId, notification);
        notificationManager.cancel(notifiId);
    }
    public void loadUser(final String openId){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("open_id",openId);
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_CHAT_GET_USER_BY_OPENID,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                User user=User.parse(responsePojo.getData());
                tempUser.put(openId,user);
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {

            }
        });
    }
}
